package cn.classTest.mall.service.impl;

import cn.classTest.mall.domain.Employee;
import cn.classTest.mall.mapper.EmployeeMapper;
import cn.classTest.mall.mapper.RoleMapper;
import cn.classTest.mall.query.EmployeeQueryObject;
import cn.classTest.mall.service.EmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.management.relation.Role;
import java.util.List;
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RoleMapper roleMapper;



    @Override
    public PageInfo<Employee> query(EmployeeQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
            List<Employee> employees = employeeMapper.queryForPage(qo);
            System.out.println(qo);
            System.out.println(employees);
            PageInfo<Employee> pageInfo = new PageInfo<>(employees);
            return pageInfo;
    }

    @Override
    public List<Employee> selectAll()  {
        return employeeMapper.selectAll();
    }

    @Override
    public void saveOrUpdate(Employee employee, Long[] roleIds) {
        if (employee.getId() != null) {
            employeeMapper.update(employee);
        } else {
            Md5Hash md5Hash = new Md5Hash(employee.getPassword());
            employee.setPassword(md5Hash.toString());
            employeeMapper.save(employee);
        }
        employeeMapper.deleteRoleWhereId(employee.getId());
        if (roleIds != null && roleIds.length != 0) {
            employeeMapper.insertEmpAndRole(employee.getId(), roleIds);
        }

    }

    @Override
    public void delete(Long id) {
        employeeMapper.delete(id);
    }

    @Override
    public Employee selectOne(Long id) {
        Employee employee = employeeMapper.selectOne(id);
        List<Role> roles = roleMapper.selectRoleByEmployeeId(id);
        employee.setRoles(roles);
        return employee;
    }
}
